<template>
  <div class="login-container">
    <div class="login-left">
      <h2>欢迎回来</h2>
      <p>登录以继续您的科研工作</p>
    </div>
    <div class="login-right">
      <div class="login-form">
        <h1>用户登录</h1>
        <el-form 
          ref="loginFormRef" 
          :model="loginForm" 
          :rules="loginRules" 
          label-width="0px"
          @submit.prevent="handleLogin"
        >
          <el-form-item prop="username">
            <el-input 
              v-model="loginForm.username" 
              placeholder="请输入用户名或邮箱"
              prefix-icon="User"
              size="large"
              clearable
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input 
              v-model="loginForm.password" 
              type="password" 
              placeholder="请输入密码"
              prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>
          
          <div class="login-options">
            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
            <el-link type="primary" @click="handleForgotPassword">忘记密码？</el-link>
          </div>
          
          <el-form-item>
            <el-button 
              type="primary" 
              size="large" 
              :loading="loading"
              @click="handleLogin"
              class="login-button"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>

        <div class="register-link">
          <span>没有账号？</span>
          <el-link
            type="primary"
            @click="goToRegister"
            >
            立即注册
          </el-link>
        </div>
        
        <div class="third-party-login">
          <p>其他登录方式</p>
          <div class="social-icons">
            <el-button circle>
              <img src="/wechat.svg" alt="微信登录" class="social-icon" />
            </el-button>
            <el-button circle>
              <img src="/github.svg" alt="GitHub登录" class="social-icon" />
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import AuthAPI from '@/utils/auth'

const router = useRouter()
const loginFormRef = ref(null)
const loading = ref(false)
const rememberMe = ref(false)

const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名或邮箱', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    loading.value = true

    // /api/v1/auth/
    const response = await AuthAPI.login({
      username: loginForm.username,
      password: loginForm.password
    })

    console.log('登录成功:', response)
    
    // token
    localStorage.setItem('token', response.access_token)

    ElMessage.success('登录成功')
    router.push({ name: 'home' })
  } catch (error) {
    console.error('登录失败:', error)
     if (error.response && error.response.status === 401) {
      // 401错误通常是用户名或密码错误
      ElMessage.error('用户名或密码错误，请重新输入')
    } else if (error.message && error.message.includes('Network Error')) {
      // 网络错误
      ElMessage.error('网络连接失败，请检查服务器是否正常运行')
    } else {
      // 其他错误
      ElMessage.error('登录失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

const goToRegister = () => {
  router.push({ name: 'register' })
}

const handleForgotPassword = () => {
  ElMessage.info('请联系管理员重置密码')
}
</script>

<style scoped>
.login-container {
  display: flex;
  height: 100vh;
  justify-content: center;
  /* align-items: center; */
}

.login-left {
  flex: 1;
  background: linear-gradient(135deg, #409eff, #67c23a);
  background-image: url('/public/auth-logo.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  overflow: hidden;
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  text-align: center;
}

.login-left h2 {
  font-size: 28px;
  margin-bottom: 10px;
}

.login-left p {
  font-size: 16px;
  opacity: 0.9;
}

.login-right {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.login-form {
  width: 100%;
  max-width: 350px;
}

.login-form h1 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.login-button {
  width: 100%;
}

.third-party-login {
  margin-top: 30px;
  text-align: center;
}

.third-party-login p {
  position: relative;
  margin-bottom: 20px;
  color: #999;
}

.third-party-login p::before,
.third-party-login p::after {
  content: "";
  position: absolute;
  top: 50%;
  width: 30%;
  height: 1px;
  background: #ddd;
}

.third-party-login p::before {
  left: 0;
}

.third-party-login p::after {
  right: 0;
}

.social-icons {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.social-icon {
  width: 20px;
  height: 20px;
}

@media (max-width: 768px) {
  .login-container {
    flex-direction: column;
    height: auto;
  }
  
  .login-left {
    padding: 30px 20px;
  }
  
  .illustration img {
    max-height: 200px;
  }
}
</style>